<!DOCTYPE html>
<html>

<head>
  <title>RtspPlay</title>
  <meta charset="UTF-8">
  <style>
    .controls {
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <div id="player">
    <video id="videoElement" controls autoplay width=1024 height=768 ></video>
  </div>

  <div class="controls">
    <label for="urlSelect">选择视频通道: </label>
    <select id="urlSelect">
      <option value="rtsp://192.168.5.10:554/stream0">微光1</option>
      <option value="rtsp://192.168.5.10:554/stream1">热成像</option>
      <option value="rtsp://192.168.5.10:554/stream2">微光2</option>
      <option value="rtsp://192.168.5.10:554/stream3">融合</option>
      <option value="rtsp://192.168.5.10:554/stream4">目标检测</option>
      <option value="rtsp://192.168.5.10:554/stream5">4K IMX485</option>
    </select>
    <button id="sendBtn">重新播放视频</button>
  </div>

  <script src="js/flv.js"></script>
  <script>
    const videoElement = document.getElementById("videoElement");
    videoElement.muted = true;

    const urlSelect = document.getElementById("urlSelect");
    const sendBtn = document.getElementById("sendBtn");
    sendBtn.onclick = async () => {
      const selectedUrl = urlSelect.value;
      const requestOptions = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rtsp_url: selectedUrl })
      };
      const response = await fetch("/setrtspurl", requestOptions);
      if (response.ok) {
        updateVideoSource("/live/stream.flv");
      }
    };

    function updateVideoSource(newUrl) {
      if (player && player.pause) {
        player.pause();
      }

      player.unload();
      player.detachMediaElement();
      player.destroy();


      const newPlayer = flvjs.createPlayer({
        type: "flv",
        url: newUrl,
        isLive: true,
        hasAudio: false,
        hasVideo: true,
        enableStashBuffer: false,
        stashInitialSize: 10,
        lazyLoad: false,
      });

      newPlayer.attachMediaElement(videoElement);
      newPlayer.load();
      newPlayer.play();

      player = newPlayer;
    }

    let player = flvjs.createPlayer({
      type: "flv",
      url: "/live/stream.flv",
      isLive: true,
      hasAudio: false,
      hasVideo: true,
      enableStashBuffer: false,
      stashInitialSize: 10,
      lazyLoad: false,
    });

    player.attachMediaElement(videoElement);
    player.load();
    player.play();

    // Add the provided code snippet here
    setInterval(() => {
      if (player.buffered.length) {
        let end = player.buffered.end(0);
        let diff = end - player.currentTime;
        if (diff >= 2.5) {
          player.currentTime = player.buffered.end(0);
        }
      }
    }, 2000);
  </script>
</body>

</html>